
export function events(Vue) {
    Vue.options = {};
   
    Vue.prototype.$on = function(event,fn){
        const vm = this;
        if(Array.isArray(event)){
            for(let i=0;i<event.length;i++){
                this.$on(event[i],fn);
            }
        }else {
            (vm._events[event] || (vm._events[event] = [])).push(fn);
        }
        return vm;
    }
    Vue.prototype.$emit = function(event){
        const vm = this;
        let cbs = vm._events[event];
        const args = toArray(arguments,1);
        if(cbs){
            for(let i=0;i<cbs.length;i++){
                try{
                    cbs.apply(vm,args);
                }catch {
                    handleError('error')
                }
            }
        }
        return vm;
    }
    Vue.prototype.$off = function(event,fn){
        const vm = this;
        if(!arguments.length){
            vm._events = Object.create(null); //移除所有事件监听器
            return vm;
        }
        if(Array.isArray(event)){
            for(let i=0;i<event.length;i++){
                this.$off(event[i],fn);
            }
            return vm;
        }
        const cbs = vm._events[event];
        if(!cbs) return vm;
        if(arguments.length ===1){
            vm._events[event] = Object.create(nul); //移出该事件的所有监听器
            return vm;
        }
        if(fn){ //只移除与fn相同的监听器
            const cbs = vm._events[event];
            let cb;
            let i = cbs.length;
            while(i--){
                cb = cbs[i];
                if(cb === fn || cb.fn === fn){
                    cbs.splice(i,1);
                    break;
                }
            }
            return vm;
        }
    }
    Vue.prototype.$once = function(event,fn){
        const vm = this;
        function on(){
            vm.$off(event,on);
            fn.apply(vm,arguments);
        }
        on.fn = fn;
        vm.$on(event,on);
        return vm;
    }
}
